#include<stdio.h>
#include<stdlib.h>
typedef struct LNode{
	int data;
	struct LNode *next;
}LNode;

int initiate(LNode **h){
	if((*h = (LNode *) malloc(sizeof(LNode))) == NULL){
		return 0;
	}
	(*h)->data = 10;
	(*h)->next = NULL;
	return 1;
}

/*
 * i <  0 return 0
 * i == 0 insert data at the end of the LinkedList
 * i >  0 insert data before the ith node or return 0 if the length < i
 */
int insert(LNode *h, int i, int data){
	int count = 0;
	LNode *new, *p;

	if(i < 0){
		return 0;
	}else if(i == 0){
		if((new = (LNode *) malloc(sizeof(LNode))) == NULL)
			return 0;
		new->data = data;
		new->next = NULL;

		p = h;
		while(p->next != NULL)
			p = p->next;
		p->next = new;
		return 1;
	}else{
		if((new = (LNode *) malloc(sizeof(LNode))) == NULL){
			return 0;
		}
		new->data = data;
		new->next = NULL;

		p = h;
		++count;
		while(count != i && p->next != NULL){
			p = p->next;
			++count;
		}

		if(p->next == NULL && count != i)
			return 0;

		new->next = p->next;
		p->next = new;
		return 1;
	}
}

int get(LNode *h, int i, int *dp){
	if(i <= 0)
		return 0;
	
	int count = 0;
	LNode *p = NULL;
	p = h;
	++count;
	while(count != i && p->next != NULL){
		p = p->next;
		++count;
	}

	if(count !=i)
		return 0;
	
	*dp = p->next->data;
	return 1;
	
}

int delete(LNode *h, int i){
	if(i <= 0){
		return 0;
	}

	int count = 0;
	LNode *p = NULL;
	p = h;
	++count;

	while(count != i && p->next != NULL){
		p = p->next;
		++count;
	}

	if(p->next == NULL && count != i){
		return 0;
	}

	LNode *t = p->next;
	p->next = t->next;
	free(t);
	return 1;
}
    
int print(LNode *head){
	LNode *t;
	t = head->next;
	while(t != NULL){
		printf("%d ", t->data);
		t = t->next;
	}

	printf("\n");
	return 1;
}

int converse(LNode *head){
	LNode *p = head->next;
	LNode *t = NULL;
	head->next = NULL;

	while(p != NULL){
		t = p->next;
		p->next = head->next;
		head->next = p;
		p = t;
	}
	return 1;
}
		
int createL(LNode **link){
	if(!initiate(link)){
		printf("failed to initialiate");
		return 0;
	}
	
	LNode *head = *link;
	int data = 0;
	printf("Enter the data insert to the List:");
	do{
		scanf("%d", &data);
		if(data == 0)
			continue;
		if(!insert(head, 0, data)){
			printf("Insert failed!\n");
			return 0;
		}
       	}while(data != 0);

	return 1;
}

int mergeQL(LNode *h1, LNode *h2){
	LNode *p1, *p2, *t;
	p1 = h1->next;
	p2 = h2->next;
	t = h1;

	while(p1 != NULL && p2 != NULL){
		if(p1->data >= p2->data){
			t->next = p2;
			p2 = p2->next;
			t = t->next;
			t->next = p1;
		}else{
			t = p1;
			p1 = p1->next;
		}
	}

	if(p1 == NULL){
		t->next = p2;
	}

	free(h2);
	return 1;
}

int main(){
	LNode *h1, *h2;
	if(!createL(&h1)){
		return 0;
	}
	print(h1);

	delete(h1, 2);
	print(h1);
	return 1;
}
